
package Chatter::API::Controller::threads;

use Moose;
use Data::Dumper;
BEGIN { extends 'Catalyst::Controller'; }

# スレッド一覧照会
sub root :Path('') {
  my ($self, $c) = @_;

  # 検索パラメータ
  my $defaultSize = 30;
  my $size = $c->request->query_params->{'size'} || $defaultSize;
  $size = $size =~ /[^\d]/ ?
          $size = $defaultSize :
          $size > $defaultSize ? $defaultSize : $size;
  my $sort = $c->request->query_params->{'sort'};
  $sort = 'posted' if(lc($sort) ne 'posted' && lc($sort) ne 'updated' && lc($sort) ne 'threshold');
  $sort = $sort eq 'threshold' ? 'replyCount' : $sort;
  my $threshold = $c->request->query_params->{'threshold'} || 0;
  $threshold = $threshold =~ /[^\d]/ ? $threshold = 0 : $threshold;

  # スレッド一覧
  my $threads = $c->stash->{tThread}->search(
    {
      replyCount => { '>=' => $threshold }
    },
    {
      order_by => { -desc => $sort },
      rows => $size,
    }
  );

  my @jsons;
  while(my $thread = $threads->next){
    my $json;
    $json->{name}      = $thread->account->name;
    $json->{accountId} = $thread->account->accountId;
    $json->{threadId}  = $thread->threadId;
    $json->{tweet}     = $thread->tweet;
    $json->{posted}    = $thread->posted;
    $json->{url}       = $thread->url;
    $json->{groupId}   = $thread->groupId;
    $json->{replyCount}= $thread->replyCount;
    $json->{updated}   = $thread->updated;
    push(@jsons,$json);
  }
  $c->stash->{threads} = \@jsons;
  $c->forward('View::JSON');
}

# スレッド個別照会
sub default :LocalRegex('^(.*)$') {
  my ($self, $c) = @_;
  my $id = $c->req->captures->[0];

  # スレッド検索
  my $thread = $c->stash->{tThread}->single(
    { threadId => $id }
  );

  if($thread){
    my $json;
    $json->{name}      = $thread->account->name;
    $json->{accountId} = $thread->accountId;
    $json->{threadId}  = $thread->threadId;
    $json->{tweet}     = $thread->tweet;
    $json->{posted}    = $thread->posted;
    $json->{url}       = $thread->url;
    $json->{groupId}  = $thread->groupId;

    # 返信
    my @replies;
    my $replies = $thread->replies;
    while(my $reply = $replies->next){
      my $r;
      $r->{name} = $reply->account->name;
      $r->{accountId} = $reply->account->accountId;
      $r->{tweet} = $reply->tweet;
      $r->{posted} = $reply->posted;
      push(@replies, $r);
    }
    $json->{replies}    = \@replies;
    $c->stash->{thread} = $json;

  } else {
    $c->stash->{thread} = undef;
  }
  #$c->log->debug(Dumper($c->stash->{thread}));
  $c->forward('View::JSON');
}

__PACKAGE__->meta->make_immutable;
1;

